 'use strict';
const {appid, secret, getToken} = require("wx-common")
 
exports.main = async (event, context) => {
	// 初始化数据库
	const db = uniCloud.database() 
	
	// jscode2session
	const { code } = event
	
	const res = await uniCloud.httpclient.request(
		`https://api.weixin.qq.com/sns/jscode2session?appid=${appid}&secret=${secret}&js_code=${code}&grant_type=authorization_code`,
		{
			dataType:"json"
		}
	)
	// openid
	const openid = res.data.openid
	// token
	const token = getToken(openid)
	
	// 根据openid查询是否存在相同的用户
	let queryRes = await db.collection("users").where({
		openid: openid
	}).get()
	
	let userData;
	
	if(queryRes.affectedDocs<=0){
		userData = {
			openid: openid,
		}
		await db.collection("users").add(userData)
	}else{
		userData = queryRes.data[0]
	}
	
	delete userData["openid"]
	
	userData["token"] = token
	
	//返回数据给客户端
	return {
		code: 200,
		data: userData
	}
};
